package com.sky.controller.admin;

import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.exception.BaseException;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Collection;
import java.util.List;
import java.util.Set;

/**
 * 菜品管理
 */
@RestController
@RequestMapping("/admin/dish")
@Api(tags = "菜品相关接口")
@Slf4j
public class DishController {

    @Autowired
    private DishService dishService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     *新增菜品
     * @param dishDTO
     * @return
     */
    @PostMapping
    @ApiOperation("新增菜品")
    public Result save(@RequestBody DishDTO dishDTO){
        if (dishDTO == null){
            throw new BaseException(400, "参数错误");
        }
        if (dishDTO.getName() == null){
            throw new BaseException(400, "name不能为空");
        }
        if (dishDTO.getPrice() == null){
            throw new BaseException(400, "price不能为空");
        }
        if (dishDTO.getCategoryId() == null){
            throw new BaseException(400, "categoryId不能为空");
        }
        log.info("新增菜品：{}",dishDTO);
        dishService.saveWithFlavor(dishDTO);

        //清理缓存数据
        String key="dish_"+dishDTO.getCategoryId();
        cleanCache(key);

        return Result.success();
    }

    /**
     * 菜品分页查询
     * @param dishPageQueryDTO
     * @return
     */
    @GetMapping("/page")
    @ApiOperation("菜品分页查询")
    public Result<PageResult> page(DishPageQueryDTO dishPageQueryDTO){
        Integer page = dishPageQueryDTO.getPage();
        Integer pageSize = dishPageQueryDTO.getPageSize();
        if (page == null || page < 0){
            throw new BaseException(400, "page参数有误");
        }

        if (pageSize == null || pageSize < 0){
            throw new BaseException(400, "pageSize参数有误");
        }

        // 1. 校验categoryId格式（若存在）
        if (dishPageQueryDTO.getCategoryId() != null) {
            // 正则校验：必须是正整数（^[1-9]\\d*$）
            if (!dishPageQueryDTO.getCategoryId().matches("^[1-9]\\d*$")) {
                throw new BaseException(400, "categoryId为非数字");
            }
            // 2. 转换为Integer，存入categoryIdInt
            try {
                Integer categoryIdInt = Integer.parseInt(dishPageQueryDTO.getCategoryId());
                dishPageQueryDTO.setCategoryIdInt(categoryIdInt);
            } catch (NumberFormatException e) {
                // 理论上不会触发（已正则校验），预防意外
                throw new BaseException(400, "categoryId为非数字");
            }
        }

        // 3. 校验status（若存在，假设status只能是0或1）
        if (dishPageQueryDTO.getStatus() != null) {
            if (dishPageQueryDTO.getStatus() < 0 || dishPageQueryDTO.getStatus() > 1) {
                throw new BaseException(400, "status为无效值");
            }
        }

        log.info("菜品分页查询:{}",dishPageQueryDTO);
        PageResult pageResult=dishService.pageQuery(dishPageQueryDTO);
        return Result.success(pageResult);
    }

    /**
     * 菜品批量删除
     * @param ids
     * @return
     */
    @DeleteMapping
    @ApiOperation("菜品批量删除")
    public Result delete(@RequestParam List<Long> ids){
        if (ids == null || ids.size() == 0){
            throw new BaseException(400, "ids不能为空");
        }
        log.info("菜品批量删除：{}",ids);
        dishService.deleteBatch(ids);

        //删除全部的菜品缓存数据，所有以dish_开头的key
        cleanCache("dish_*");

        return Result.success();
    }

    /**
     * 根据id查询菜品
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    @ApiOperation("根据id查询菜品")
    public Result<DishVO> getById(@PathVariable Long id){
        if(id == null){
            throw new BaseException(400, "id不能为空");
        }
        log.info("根据id查询菜品：{}",id);
        DishVO dishVO = dishService.getByIdWithFlavor(id);
        return Result.success(dishVO);
    }

    /**
     * 修改菜品
     * @param dishDTO
     * @return
     */
    @PutMapping
    @ApiOperation("修改菜品")
    public Result update(@RequestBody DishDTO dishDTO){
        // 传入id不能为空
        if (dishDTO.getId() == null){
            throw new BaseException(400, "id不能为空");
        }
        // 传入的categoryId不能为空
        if (dishDTO.getCategoryId() == null){
            throw new BaseException(400, "categoryId不能为空");
        }
        if (dishDTO.getName() == null){
            throw new BaseException(400, "name不能为空");
        }

        log.info("修改菜品:{}",dishDTO);
        dishService.updateWithFlavor(dishDTO);

        //删除全部的菜品缓存数据，所有以dish_开头的key
        cleanCache("dish_*");

        return  Result.success();
    }

    /**
     * 菜品起售、停售
     * @return
     */
    @PostMapping("status/{status}")
    public Result startStop(@PathVariable Integer status,Long id){
        // id为空
        if(id == null){
            throw new BaseException(400, "id不能为空");
        }
        // id为0（无效id）
        if(id == 0){
            throw new BaseException(400, "id为无效值");
        }

        log.info("起售停售菜品状态:{},{}",status,id);
        dishService.startStopSale(status,id);

        ////删除全部的菜品缓存数据，所有以dish_开头的key
        cleanCache("dish_*");

        return Result.success();
    }

    /**
     * 根据分类id查询菜品
     * @param categoryId
     * @return
     */
    @GetMapping("/list")
    @ApiOperation("根据分类id查询菜品")
    public Result<List<Dish>> list(Long categoryId){
        if(categoryId == null){
            throw new BaseException(400, "categoryId不能为空");
        }
        List<Dish> list=dishService.list(categoryId);
        return Result.success(list);
    }

    public void cleanCache(String pattern){
        Set keys = redisTemplate.keys(pattern);
        redisTemplate.delete(keys);
    }
}

